﻿using System;
using System.Drawing;
using System.Windows.Forms;

namespace 瓦片截图
{
    public class OverlayForm : Form
    {
        public Rectangle SelectionRect { get; set; }
        private const int handleSize = 15;
        private readonly Pen redPen = new Pen(Color.Red, 2);
        private readonly Brush handleBrush = Brushes.Red;

        private bool isDragging = false;
        private Point dragStart;
        private int dragHandle = -1;

        // 新增的文本框和标签控件
        private TextBox txtWidth;
        private TextBox txtHeight;
        private Label lblWidth;
        private Label lblHeight;
        private const int textBoxWidth = 50;
        private const int textBoxHeight = 20;
        private const int margin = 1;
        private const int textBoxOffsetY = 25;

        public OverlayForm()
        {
            InitializeForm();
            InitializeSelectionRect();
            InitializeTextControls();
        }

        private void InitializeForm()
        {
            this.FormBorderStyle = FormBorderStyle.None;
            this.WindowState = FormWindowState.Maximized;
            this.TopMost = true;
            this.ShowInTaskbar = false;
            this.BackColor = Color.Magenta;
            this.TransparencyKey = Color.Magenta;
            this.DoubleBuffered = true;
        }

        private void InitializeSelectionRect()
        {
            SelectionRect = new Rectangle(100, 100, 300, 200);
        }

        private void InitializeTextControls()
        {
            // 宽度标签
            lblWidth = new Label
            {
                Text = "宽度:",
                ForeColor = Color.White,
                BackColor = Color.Red,
                AutoSize = false,
                Size = new Size(40, 20),
                TextAlign = ContentAlignment.MiddleCenter,
                Location = new Point(SelectionRect.Left, SelectionRect.Top - textBoxOffsetY)
            };

            // 宽度文本框
            txtWidth = new TextBox
            {
                Text = SelectionRect.Width.ToString(),
                Width = textBoxWidth,
                Height = textBoxHeight,
                Location = new Point(lblWidth.Right + margin, SelectionRect.Top - textBoxOffsetY)
            };
            txtWidth.TextChanged += TxtWidth_TextChanged;
            txtWidth.KeyPress += TxtNumeric_KeyPress;
            txtWidth.LostFocus += TxtDimension_LostFocus;

            // 高度标签
            lblHeight = new Label
            {
                Text = "高度:",
                ForeColor = Color.White,
                BackColor = Color.Red,
                AutoSize = false,
                Size = new Size(40, 20),
                TextAlign = ContentAlignment.MiddleCenter,
                Location = new Point(txtWidth.Right + margin * 2, SelectionRect.Top - textBoxOffsetY)
            };

            // 高度文本框
            txtHeight = new TextBox
            {
                Text = SelectionRect.Height.ToString(),
                Width = textBoxWidth,
                Height = textBoxHeight,
                Location = new Point(lblHeight.Right + margin, SelectionRect.Top - textBoxOffsetY)
            };
            txtHeight.TextChanged += TxtHeight_TextChanged;
            txtHeight.KeyPress += TxtNumeric_KeyPress;
            txtHeight.LostFocus += TxtDimension_LostFocus;

            // 添加控件
            this.Controls.Add(lblWidth);
            this.Controls.Add(txtWidth);
            this.Controls.Add(lblHeight);
            this.Controls.Add(txtHeight);
        }

        private void TxtNumeric_KeyPress(object sender, KeyPressEventArgs e)
        {
            // 只允许输入数字和退格键
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void TxtDimension_LostFocus(object sender, EventArgs e)
        {
            // 失去焦点时更新矩形尺寸
            UpdateRectangleFromTextboxes();
        }

        private void TxtWidth_TextChanged(object sender, EventArgs e)
        {
            if (this.ContainsFocus && txtWidth.Focused)
            {
                UpdateRectangleFromTextboxes();
            }
        }

        private void TxtHeight_TextChanged(object sender, EventArgs e)
        {
            if (this.ContainsFocus && txtHeight.Focused)
            {
                UpdateRectangleFromTextboxes();
            }
        }

        private void UpdateRectangleFromTextboxes()
        {
            int width, height;

            if (int.TryParse(txtWidth.Text, out width) && width > 10 &&
                int.TryParse(txtHeight.Text, out height) && height > 10)
            {
                SelectionRect = new Rectangle(SelectionRect.X, SelectionRect.Y, width, height);
                this.Invalidate();
            }
            else
            {
                // 恢复有效值
                txtWidth.Text = SelectionRect.Width.ToString();
                txtHeight.Text = SelectionRect.Height.ToString();
            }
        }

        private void UpdateTextControlsPosition()
        {
            // 更新文本框位置，使其始终位于矩形左上角上方
            lblWidth.Location = new Point(SelectionRect.Left, SelectionRect.Top - textBoxOffsetY);
            txtWidth.Location = new Point(lblWidth.Right + margin, SelectionRect.Top - textBoxOffsetY);
            lblHeight.Location = new Point(txtWidth.Right + margin * 2, SelectionRect.Top - textBoxOffsetY);
            txtHeight.Location = new Point(lblHeight.Right + margin, SelectionRect.Top - textBoxOffsetY);

            // 更新文本框值
            txtWidth.Text = SelectionRect.Width.ToString();
            txtHeight.Text = SelectionRect.Height.ToString();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            // 绘制选择矩形
            e.Graphics.DrawRectangle(redPen, SelectionRect);

            // 绘制9个锚点
            DrawHandle(e.Graphics, SelectionRect.Left, SelectionRect.Top);        // 0:左上
            DrawHandle(e.Graphics, SelectionRect.Left + SelectionRect.Width / 2, SelectionRect.Top); // 1:中上
            DrawHandle(e.Graphics, SelectionRect.Right, SelectionRect.Top);       // 2:右上
            DrawHandle(e.Graphics, SelectionRect.Right, SelectionRect.Top + SelectionRect.Height / 2); // 3:右中
            DrawHandle(e.Graphics, SelectionRect.Right, SelectionRect.Bottom);   // 4:右下
            DrawHandle(e.Graphics, SelectionRect.Left + SelectionRect.Width / 2, SelectionRect.Bottom); // 5:中下
            DrawHandle(e.Graphics, SelectionRect.Left, SelectionRect.Bottom);    // 6:左下
            DrawHandle(e.Graphics, SelectionRect.Left, SelectionRect.Top + SelectionRect.Height / 2); // 7:左中
            DrawHandle(e.Graphics, SelectionRect.Left + SelectionRect.Width / 2, SelectionRect.Top + SelectionRect.Height / 2); // 8:中心
        }

        private void DrawHandle(Graphics g, int x, int y)
        {
            g.FillRectangle(handleBrush, x - handleSize / 2, y - handleSize / 2, handleSize, handleSize);
        }

        private int GetHandleAtPoint(Point pt)
        {
            // 检查是否点击了某个锚点
            if (IsInHandle(pt, SelectionRect.Left, SelectionRect.Top)) return 0;       // 左上
            if (IsInHandle(pt, SelectionRect.Left + SelectionRect.Width / 2, SelectionRect.Top)) return 1; // 中上
            if (IsInHandle(pt, SelectionRect.Right, SelectionRect.Top)) return 2;      // 右上
            if (IsInHandle(pt, SelectionRect.Right, SelectionRect.Top + SelectionRect.Height / 2)) return 3; // 右中
            if (IsInHandle(pt, SelectionRect.Right, SelectionRect.Bottom)) return 4;   // 右下
            if (IsInHandle(pt, SelectionRect.Left + SelectionRect.Width / 2, SelectionRect.Bottom)) return 5; // 中下
            if (IsInHandle(pt, SelectionRect.Left, SelectionRect.Bottom)) return 6;    // 左下
            if (IsInHandle(pt, SelectionRect.Left, SelectionRect.Top + SelectionRect.Height / 2)) return 7; // 左中
            if (IsInHandle(pt, SelectionRect.Left + SelectionRect.Width / 2, SelectionRect.Top + SelectionRect.Height / 2)) return 8; // 中心

            return -1;
        }

        private bool IsInHandle(Point pt, int x, int y)
        {
            return pt.X >= x - handleSize && pt.X <= x + handleSize &&
                   pt.Y >= y - handleSize && pt.Y <= y + handleSize;
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);

            if (e.Button == MouseButtons.Left)
            {
                dragHandle = GetHandleAtPoint(e.Location);

                if (dragHandle != -1)
                {
                    isDragging = true;
                    dragStart = e.Location;
                }
            }
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);

            // 设置鼠标指针样式
            int handle = GetHandleAtPoint(e.Location);
            if (handle != -1)
            {
                switch (handle)
                {
                    case 0:
                    case 4: this.Cursor = Cursors.SizeNWSE; break;
                    case 1:
                    case 5: this.Cursor = Cursors.SizeNS; break;
                    case 2:
                    case 6: this.Cursor = Cursors.SizeNESW; break;
                    case 3:
                    case 7: this.Cursor = Cursors.SizeWE; break;
                    case 8: this.Cursor = Cursors.SizeAll; break;
                }
            }
            else
            {
                this.Cursor = Cursors.Default;
            }

            if (isDragging)
            {
                int dx = e.X - dragStart.X;
                int dy = e.Y - dragStart.Y;

                Rectangle newRect = SelectionRect;

                switch (dragHandle)
                {
                    case 0: // 左上
                        newRect.X += dx;
                        newRect.Y += dy;
                        newRect.Width -= dx;
                        newRect.Height -= dy;
                        break;
                    case 1: // 中上
                        newRect.Y += dy;
                        newRect.Height -= dy;
                        break;
                    case 2: // 右上
                        newRect.Y += dy;
                        newRect.Width += dx;
                        newRect.Height -= dy;
                        break;
                    case 3: // 右中
                        newRect.Width += dx;
                        break;
                    case 4: // 右下
                        newRect.Width += dx;
                        newRect.Height += dy;
                        break;
                    case 5: // 中下
                        newRect.Height += dy;
                        break;
                    case 6: // 左下
                        newRect.X += dx;
                        newRect.Width -= dx;
                        newRect.Height += dy;
                        break;
                    case 7: // 左中
                        newRect.X += dx;
                        newRect.Width -= dx;
                        break;
                    case 8: // 中心
                        newRect.X += dx;
                        newRect.Y += dy;
                        break;
                }

                if (newRect.Width > 10 && newRect.Height > 10)
                {
                    SelectionRect = newRect;
                    dragStart = e.Location;
                    UpdateTextControlsPosition();
                    this.Invalidate();
                }
            }
        }

        protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseUp(e);
            isDragging = false;
        }

        protected override void OnLocationChanged(EventArgs e)
        {
            base.OnLocationChanged(e);
            UpdateTextControlsPosition();
        }
    }
}